﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using uno.util;
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.uno;
using unoidl.com.sun.star.bridge;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.text;
using unoidl.com.sun.star.beans;
using unoidl.com.sun.star.util;
public partial class Manage_basisset_ClassResource : AdminPageBase
{
    int classId;
   
    protected void Page_Load(object sender, EventArgs e)
    {
        CheckAdmin();
        GetUserPermisions();
        GetClassId();
        if (add == 1)
        {
            btnsave.Enabled = true;
            btnupload.Enabled = true;
        }
        else
        {
            btnsave.Enabled = false;
            btnupload.Enabled = false;
        }
      
    }
    protected void CheckAdmin()
    {
        if (AdminSessionHelper.UserDetails == null)
        {
            JsHelper.TopAlertRedirect("请先登录", "../login.aspx", this.Page);
        }


    }
    protected void GetClassId()
    {
        if (Request.QueryString["id"] != null)
        {
            classId = Convert.ToInt32(Request.QueryString["id"]);
            BindClassResource();
        }
       
    }
    protected void BindClassResource()
    {
        DataSet ds = jtDataAccess.GetClassDetail(classId);
        if (CoreTools.CheckDataSet(ds))
        {

            // GridView绑定并显示数据
            // this.GridView1.DataSource = ds.Tables[0];
            // this.GridView1.DataBind();
            GridviewControl.GridViewDataBind(this.GridView1, ds.Tables[0]);
        }
        else
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ClassDetailId");
            dt.Columns.Add("Title");
            dt.Columns.Add("OriginalName");
            dt.Columns.Add("Size");
            dt.Columns.Add("");

            GridviewControl.GridViewDataBind(this.GridView1, dt);
        }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //首先判断是否是数据行
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //当鼠标停留时更改背景色
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FCFDEE'");
            //当鼠标移开时还原背景色
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
        }
    }
  
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int flag = 0;
        if (e.CommandName == "modify")
        {
           // Response.Redirect("ResourceDetail.aspx?id=" + int.Parse(e.CommandArgument.ToString())+"&MenuId="+MenuId);
            hdfClassDetailId.Value = e.CommandArgument.ToString();
            BindClassDetail(int.Parse(e.CommandArgument.ToString()));
        }
        else if (e.CommandName == "Del")
        {

            int  ClassDetailId = int.Parse(e.CommandArgument.ToString());

            flag = jtDataAccess.OpClassDetail(JTDataAccess.OpType.Delete,ClassDetailId,classId,"","","","",0);

            switch (flag)
            {

                case -1:
                    CoreTools.PageAlert("该课件已经在使用，不允许删除！");
                   //ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.PageAlert("该课件已经在使用，不允许删除！"), false);
                    break;
                case 0:
                   CoreTools.PageAlert("删除失败， 请确认课程基本信息已保存。");
                   //ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.PageAlert("删除失败！"), false);
                    break;
                default:
                    CoreTools.PageAlert("删除成功！");
                   // ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.PageAlert("删除成功！"), false);
                    BindClassResource();
                    break;
            }

        }
    }
    protected void BindClassDetail(int classDetailId)
    {
        if (classDetailId != 0)
        {
            DataSet ds = jtDataAccess.GetList("ClassDetail", "ClassDetailId=" + classDetailId, "ClassDetailId");
            if (CoreTools.CheckDataSet(ds))
            {
                txtOriginalName.Text = ds.Tables[0].Rows[0]["OriginalName"].ToString();
                txtTitle.Text = ds.Tables[0].Rows[0]["Title"].ToString();
                txtIntro.Text = ds.Tables[0].Rows[0]["Intro"].ToString();
                string playurl = ConfigHelper.VideoUploadPath.Replace("~/", "../../");
                string extensionName = System.IO.Path.GetExtension(ds.Tables[0].Rows[0]["Url"].ToString());
                ViewState["tvcURL"] = ds.Tables[0].Rows[0]["Url"].ToString();
                ViewState["fileSize"] = ds.Tables[0].Rows[0]["Size"].ToString();
                ViewState["OriginalName"] = ds.Tables[0].Rows[0]["OriginalName"].ToString(); 
				string ClassResourceType="";
				ClassResourceType=CoreTools.GetClassResourceType(extensionName.ToLower());
				if(ClassResourceType.Equals("swf"))
                    lblPlay.Text = Play.TVCPlayer("500", "400", playurl + ds.Tables[0].Rows[0]["Url"].ToString());
                else if (ClassResourceType.Equals("video"))
                    lblPlay.Text = Play.MediaPlayer("500", "400", playurl + ds.Tables[0].Rows[0]["Url"].ToString());
                else if (ClassResourceType.Equals("officeDocument"))
                {
                    string fpath = ConfigHelper.SWFFilePath.Replace("~/", "../../") + ds.Tables[0].Rows[0]["Url"].ToString().Replace(extensionName, ".swf");
                    lblPlay.Text = Play.FlexPaperViewer(660, 400, fpath);
                       
                }
				 else if (ClassResourceType.Equals("Image")){
					lblPlay.Text ="<img src="+ConfigHelper.ImgUploadPath.Replace("~/", "../../")+ds.Tables[0].Rows[0]["Url"].ToString()+" wdith=300px height=200px>"; 
				}
            }
        }
    }
    protected void btnupload_Click(object sender, EventArgs e)
    {
        if (InputFile1.HasFile == true)
        {
            if (InputFile1.FileName != null)
            {
                if (InputFile1.FileName.Length == 0)
                {
                    CoreTools.PageAlert("请选择要上传文件");
                    //ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.PageAlert("请选择要上传文件"), false);

                }
                else
                {
                    string fileName = Guid.NewGuid().ToString();
                    int position = InputFile1.FileName.LastIndexOf(".");
                    if (position == -1)
                    {
                        CoreTools.PageAlert("上传的文件格式不正确！");
                        //ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.PageAlert("上传的文件格式不正确！"), false);
                    }
                    else
                    {
                        string OriginalName = this.InputFile1.FileName;//获取上传文件的文件名,包括后缀
                        string extensionName = InputFile1.FileName.Substring(position);
                        string filePath = "";
						string ClassResourceType="";
				       ClassResourceType=CoreTools.GetClassResourceType(extensionName.ToLower());
                        if (ClassResourceType.Equals("swf"))
                            filePath = ConfigHelper.VideoUploadPath;
                        else if (ClassResourceType.Equals("video"))
                            filePath = ConfigHelper.VideoUploadPath;
                        else if (ClassResourceType.Equals("officeDocument"))
                            filePath = ConfigHelper.FileUploadPath;
						else if (ClassResourceType.Equals("Image"))
                            filePath = ConfigHelper.ImgUploadPath;
                        fileName = fileName + extensionName;
                        string original = fileName;
                        if (filePath != "")
                        {
                            InputFile1.MoveTo(Server.MapPath(filePath + fileName), Brettle.Web.NeatUpload.MoveToOptions.Overwrite);
                            int FileSize = int.Parse(((float)(InputFile1.ContentLength / 1024)).ToString()); //获取文件大小,单位是KB
                            ViewState["tvcURL"] = fileName;
                            ViewState["fileSize"] = FileSize;
                            ViewState["OriginalName"] = OriginalName;
                            string playurl = ConfigHelper.VideoUploadPath.Replace("~/", "../../");
                            if (ClassResourceType.Equals("swf"))
                                lblPlay.Text = Play.TVCPlayer("500", "400", playurl + fileName);
                            else if (ClassResourceType.Equals("officeDocument"))
                            {
                                string sourceFile = HttpContext.Current.Request.MapPath(ConfigHelper.FileUploadPath.Replace("~/", "../../") + original );
                                string targetFile = HttpContext.Current.Request.MapPath(ConfigHelper.FileUploadPath.Replace("~/", "../../") + original.Substring(0,original.IndexOf('.')) + ".pdf");

                                // word文件
                                if ( extensionName.ToUpper() == ".DOC" || extensionName.ToUpper() == ".DOCX" )
                                {                                   
                                    office2pdf.DOCConvertToPDF(sourceFile, targetFile);
                                }

                                // excel文件
                                if (extensionName.ToUpper() == ".XLS" || extensionName.ToUpper() == ".XLSX" )
                                {
                                    office2pdf.XLSConvertToPDF(sourceFile, targetFile);
                                }

                                // powerpoint文件
                                if ( extensionName.ToUpper() == ".PPT" || extensionName.ToUpper() == ".PPTX")
                                {
                                    office2pdf.PPTConvertToPDF(sourceFile, targetFile);
                                }

                                fileName = original.Substring(0, original.IndexOf('.')) + ".pdf";
                                extensionName = ".pdf";

                                fileToSWF(fileName, extensionName);
                                string fpath = ConfigHelper.SWFFilePath.Replace("~/", "../../") + fileName.Replace(extensionName, ".swf");
                                lblPlay.Text = Play.FlexPaperViewer(660, 400, fpath);

                                CoreTools.FilePicDelete(sourceFile);
                                CoreTools.FilePicDelete(HttpContext.Current.Request.MapPath(ConfigHelper.FileUploadPath.Replace("~/", "../../") + fileName));
                                CoreTools.FilePicDelete(HttpContext.Current.Request.MapPath(ConfigHelper.PDFFilePath.Replace("~/", "../../") + fileName.Replace(extensionName, ".pdf")));


                            }
                            else if (ClassResourceType.Equals("video"))
                                lblPlay.Text = Play.MediaPlayer("500", "400", playurl + fileName);
							 else if (ClassResourceType.Equals("Image"))
                            {
                                lblPlay.Text = "<img src=" + ConfigHelper.ImgUploadPath.Replace("~/", "../../") + fileName + " wdith=300px height=200px>";
							}
                            else
                                CoreTools.PageAlert("上传的文件格式不正确！");
                            //ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.PageAlert("上传的文件格式不正确！"), false);
                        }
                        else
                            CoreTools.PageAlert("上传的文件格式不正确！");
                        //ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.PageAlert("上传的文件格式不正确！"), false);
                    }
                }
            }

        }
        else
            CoreTools.PageAlert("请选择要上传文件");
    }
    protected void fileToSWF(string fileName, string extensionName)
    {
        if (extensionName == ".pdf")
        {
            string cmdStr = HttpContext.Current.Request.MapPath("../../FlexPaper/pdf2swf.exe");
            string savePath = HttpContext.Current.Server.MapPath("../../swf");
            string filePath = HttpContext.Current.Request.MapPath(ConfigHelper.FileUploadPath.Replace("~/", "../../") + fileName);
            string args = "  -t " + filePath + "  -o " + savePath + "\\" + fileName.Replace(extensionName, ".swf");
            //分页
            // string args = "  -t " + filePath + "  -o " + savePath + "\\Pager%.swf -f -T 9 -t -s storeallcharacters";
            PDF2SWFCmd.ExecuteCmd(cmdStr, args);
        }
        else  try
        {
            string excelFile = "file:///" + HttpContext.Current.Request.MapPath(ConfigHelper.FileUploadPath.Replace("~/", "../../") + fileName).Replace("\\","/");
            string pdfFile = "file:///" + HttpContext.Current.Request.MapPath(ConfigHelper.PDFFilePath.Replace("~/", "../../") + fileName.Replace(extensionName, ".pdf")).Replace("\\", "/");


            // Start OpenOffce or get a reference to an existing session
            XComponentContext localContext = Bootstrap.bootstrap();
            XMultiServiceFactory multiServiceFactory = (XMultiServiceFactory)localContext.getServiceManager();
            XComponentLoader componentLoader = (XComponentLoader)multiServiceFactory.createInstance("com.sun.star.frame.Desktop");

            // Open file hidden in read-only mode
            PropertyValue[] loadProps = new PropertyValue[2];
            loadProps[0] = new PropertyValue();
            loadProps[0].Name = "ReadOnly";
            loadProps[0].Value = new uno.Any(true);
            loadProps[1] = new PropertyValue();
            loadProps[1].Name = "Hidden";
            loadProps[1].Value = new uno.Any(true);

            // Open the file
            XComponent sourceDoc = componentLoader.loadComponentFromURL(excelFile, "_blank", 0, loadProps);

            // Conversion parameters - overwrite existing file, use PDF exporter
            PropertyValue[] conversionProperties = new PropertyValue[3];
            conversionProperties[0] = new PropertyValue();
            conversionProperties[0].Name = "Overwrite";
            conversionProperties[0].Value = new uno.Any(true);
            conversionProperties[1] = new PropertyValue();
            conversionProperties[1].Name = "FilterName";
            conversionProperties[1].Value = new uno.Any("writer_pdf_Export");

            // Set PDF export parameters
            PropertyValue[] filterData = new PropertyValue[3];

            // JPEG compression quality 70
            filterData[0] = new PropertyValue();
            filterData[0].Name = "Quality";
            filterData[0].Value = new uno.Any(70);
            filterData[0].State = PropertyState.DIRECT_VALUE;

            // Max image resolution 300dpi
            filterData[1] = new PropertyValue();
            filterData[1].Name = "ReduceImageResolution";
            filterData[1].Value = new uno.Any(true);
            filterData[1].State = PropertyState.DIRECT_VALUE;
            filterData[2] = new PropertyValue();
            filterData[2].Name = "MaxImageResolution";
            filterData[2].Value = new uno.Any(300);
            filterData[2].State = PropertyState.DIRECT_VALUE;

            conversionProperties[2] = new PropertyValue();
            conversionProperties[2].Name = "FilterData";
            conversionProperties[2].Value = new uno.Any(filterData.GetType(), filterData);

            // Save as PDF
            XStorable xstorable = (XStorable)sourceDoc;
            xstorable.storeToURL(pdfFile, conversionProperties);

            // Close document
            ((XCloseable)sourceDoc).close(false);
            ((XCloseable)xstorable).close(false);
            string cmdStr1 = HttpContext.Current.Server.MapPath("../../FlexPaper/pdf2swf.exe");
            string savePath1 = HttpContext.Current.Server.MapPath("../../swf");
            string pdffilepath = HttpContext.Current.Request.MapPath(ConfigHelper.PDFFilePath.Replace("~/", "../../") + fileName.Replace(extensionName, ".pdf")).Replace("\\", "/");
            string args1 = "  -t " + pdffilepath + "  -o " + savePath1 + "\\" + fileName.Replace(extensionName, ".swf");
            //分页
            // string args = "  -t " + filePath + "  -o " + savePath + "\\Pager%.swf -f -T 9 -t -s storeallcharacters";
            PDF2SWFCmd.ExecuteCmd(cmdStr1, args1);
        }
        catch (unoidl.com.sun.star.uno.Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

    }
 
    protected void btnsave_Click(object sender, EventArgs e)
    {
        int ClassDetailId = Convert.ToInt32(hdfClassDetailId.Value);
        string Title = txtTitle.Text.Trim();
        string intro = txtIntro.Text.Trim();
       // string OriginalName = txtOriginalName.Text.Trim();
        string url = "";
        int size = 0;
        string OriginalName = "";
        if (ViewState["tvcURL"] != null)
            url=ViewState["tvcURL"].ToString();
        if (ViewState["fileSize"]!=null)
            size=Convert.ToInt32(ViewState["fileSize"].ToString());
        if (ViewState["OriginalName"] != null)
            OriginalName = ViewState["OriginalName"].ToString();
        if (Title == "")
        {
           // CoreTools.PageAlert("标题不能为空");
            txtTitle.Focus();
        }
        else if (!CoreTools.ProcessSqlStr(Title, 0))
        {
            CoreTools.PageAlert(ConfigHelper.ProcessSqlStrErroMsg);
            //ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.PageAlert(ConfigHelper.ProcessSqlStrErroMsg), false);
            txtTitle.Focus();
        }
        else if (!CoreTools.ProcessSqlStr(OriginalName, 0))
        {
            CoreTools.PageAlert(ConfigHelper.ProcessSqlStrErroMsg);
            //ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.PageAlert(ConfigHelper.ProcessSqlStrErroMsg), false);
            txtOriginalName.Focus();
        }
        else
        {
            JTDataAccess.OpType OpType;
            if (ClassDetailId == 0)
            {
                OpType = JTDataAccess.OpType.Insert;

            }
            else
            {
                OpType = JTDataAccess.OpType.Update;

            }

            int flag = jtDataAccess.OpClassDetail(OpType, ClassDetailId, classId, Title,intro, OriginalName, url, size);

            switch (flag)
            {
                case -1:
                    CoreTools.PageAlert("操作失败，已经存在相同名称或编号的课程课件！");
                    // ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.PageAlert("操作失败，已经存在相同名称或编号的课程课件！"), false);
                    break;
                case 0:
                    CoreTools.PageAlert("操作失败！");
                    //ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.PageAlert("操作失败！"), false);
                    break;
                default:
                    CoreTools.PageAlert("操作成功！");
                    // ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.PageAlert("操作成功！"), false);
                    BindClassResource();
                    break;
            }
        }
    }
    protected void btnAddClassDetail_Click(object sender, EventArgs e)
    {
        txtTitle.Text = "";
        txtOriginalName.Text = "";
        txtIntro.Text = "";
        lblPlay.Text = "";
        ViewState["tvcURL"] = "";
        ViewState["tvcURL"] = 0;
        ViewState["OriginalName"] = "";
        hdfClassDetailId.Value = "0";
    }
   
}